<?php

declare(strict_types=1);

namespace app\service\system;

use app\model\system\UserGroupModel;
use app\model\system\UserModel;
use owns\auth\UserAuth;

/**
 * 管理员分组
 */
class UserGroupService
{
    /**
     * 列表
     * @param array $param
     */
    public function list(array $param)
    {
        $list = UserGroupModel::custom($param)
            ->order('sort desc')
            ->pages($param)
            ->select();
        return list_fmt($list, UserGroupModel::custom($param)->count());
    }
    /**
     * 编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): bool
    {
        $auth = UserAuth::instance();
        if ($id) {
            $group = UserGroupModel::find($data['id']);
            if (!$group) {
                tips('无分组信息');
            }
            $group->updated_by = $auth->username();
        } else {
            $group = new UserGroupModel();
            $group->created_by = $auth->username();
        }
        $group->name = trim($data['name']);
        $this->_nameRepeat($group->name, $id);
        $group->intro = $data['intro'];
        $group->leader = trim($data['leader'] ?? '');
        $group->phone = trim($data['phone'] ?? '');
        $group->status = $data['status'];
        $group->sort = $data['sort'];
        return $group->save() ? true : false;
    }
    /**
     * 名称查重
     * @param string $name
     * @param integer $id
     */
    protected function _nameRepeat(string $name, $id = 0): void
    {
        $where = UserGroupModel::where('name', $name);
        if ($id) {
            $where->where('id', '<>', $id);
        }
        if ($where->find()) {
            tips('【' . $name . '】已被使用');
        }
    }
    /**
     * 删除
     * @param integer $id
     */
    public function delete(int $id)
    {
        if ($id == 1) {
            tips('无权限删除');
        }
        if (UserModel::where('group_id', $id)->find()) {
            tips('分组在使用中，不可删除');
        }
        return UserGroupModel::where('id', $id)->delete() ? true : false;
    }
}
